<template>
    <div class="search-container">
        <!-- 通过在外层包form标签，可在移动端使输入法右下角能显示为搜索按钮 -->
        <form action="/" class="search-form">
            <van-search
            v-model="searchText"
            show-action
            background="#3296fa"
            shape="round"
            placeholder="请输入"
            @search="onSearch"
            @cancel="$router.back()"/>
        </form>

        <!-- 搜索结果 -->
        <SearchResult v-if="isResultShow" :searchText="searchText"/>
        <!-- 搜索建议 -->
        <SearchSuggestion v-else-if="searchText" :searchText="searchText" @search="onSearch"/>
        <!-- 搜索历史 -->
        <SearchHistory v-else :histories="histories" @clearHistories="histories=[]" @search="onSearch"/>
    </div>
</template>

<script>
import SearchHistory from '@/views/search/components/SearchHistory.vue'
import SearchSuggestion from '@/views/search/components/SearchSuggestion.vue'
import SearchResult from '@/views/search/components/SearchResult.vue'
import { setItem, getItem } from '@/utils/storage'

export default {
    nema: 'Search',
    components: {
        SearchHistory,
        SearchSuggestion,
        SearchResult
    },
    data () {
        return {
            searchText: '',
            isResultShow: false,
            histories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
        }
    },
    watch: {
        histories (val) {
            setItem('TOUTIAO_SEARCH_HISTORIES', val)
        }
    },
    methods: {
        onSearch (val) {
            // 更新文本框
            this.searchText = val

            // 存储搜索历史    (数组去重)
            const index = this.histories.indexOf(val)
            if (index !== -1) {
                this.histories.splice(index, 1)
            }
            this.histories.unshift(val)
            // this.histories = [...new Set(this.histories)]

            this.isResultShow = true
        }
    }
}
</script>

<style scoped lang="less">
.search-container {
    padding-top: 108px;
    .van-search__action {
        color: #fff;
    }
    .search-form {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }
}
</style>
